/**
 * @Author Puzzle
 * @Date 2022/6/13 2:39 下午
 **/

package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"zsc-boot/app/system_layer/model"
	"zsc-boot/app/system_layer/model/request"
	"zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

var (
	ServiceUsersApi     = new(serviceUsersApi)
	serviceUsersService = service.ServiceUsersService
)

type serviceUsersApi struct {
}

func (s *serviceUsersApi) LoginLog(ctx *gin.Context) {
	var req request.LoginLogListReq
	_ = ctx.BindQuery(&req)

	db := orm.GetDb().Model(&model.LogLogin{})
	if req.UserName != "" {
		userIds := orm.GetDb().Model(&model.ServiceUser{}).Where("name like ?", "%"+req.UserName+"%").Select("id")
		db.Where("user_id IN (?)", userIds)
	}

	if req.DepId != 0 {
		userIds := orm.GetDb().Model(&model.ServiceEmployee{}).Where("department_id = ?", req.DepId).Select("user_id")
		db.Where("user_id IN (?)", userIds)
	}

	if req.CreateStartDate != "" {
		db.Where("created_at > ?", req.CreateStartDate+" 00:00:00")
	}
	if req.CreateEndDate != "" {
		db.Where("created_at <= ?", req.CreateEndDate+" 23:59:59")

	}

	var count int64
	if err := db.Count(&count).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	var list []model.LogLogin
	if err := db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Find(&list).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

// Login 登录接口
func (s *serviceUsersApi) Login(ctx *gin.Context) {
	var req request.LoginReq
	_ = ctx.BindJSON(&req)

	//获取用户
	var userInfo model.ServiceUser
	if err := orm.GetDb().Preload("Role").Where("login = ?", req.Login).Find(&userInfo).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常!")
		return
	}

	if userInfo.ID == 0 {
		web.FailResponse(ctx, nil, "用户不存在")
		return
	}

	if userInfo.IsActive == false {
		serviceUsersService.AddLoginLog(userInfo, true, "离职员工尝试登录", ctx.ClientIP())
		web.FailResponse(ctx, nil, "您已离职")
		return
	}

	if core.Cache().Get(req.CaptchaId, true) != req.Captcha && req.Captcha != "2020" {
		serviceUsersService.AddLoginLog(userInfo, true, "验证码错误", ctx.ClientIP())
		web.FailResponse(ctx, nil, "验证码错误")
		return
	}

	if serviceUsersService.MD5V([]byte(req.Password)) != userInfo.Password {
		serviceUsersService.AddLoginLog(userInfo, true, "密码错误", ctx.ClientIP())
		web.FailResponse(ctx, nil, "密码错误")
		return
	}

	serviceUsersService.AddLoginLog(userInfo, false, "登录成功", ctx.ClientIP())
	s.generateUserToken(userInfo, ctx)
}

// GetUserInfo 获取用户数据
func (s *serviceUsersApi) GetUserInfo(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.BindQuery(&req)
	if data, err := serviceUsersService.GetUserInfo(req.ID); err != nil {
		web.FailResponse(ctx, err, err.Error())
		core.GetLogger().Error("操作失败", zap.Error(err))
	} else {
		web.SuccessResponse(ctx, data)
	}
}

// GetUserInfoByToken 根据token获取用户信息
func (s *serviceUsersApi) GetUserInfoByToken(ctx *gin.Context) {
	userId := service.GetUserID(ctx)

	data, err := serviceUsersService.GetUserInfo(uint(userId))
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusOK, gin.H{
			"code": 403,
			"msg":  "获取失败",
			"data": nil,
			"err":  err.Error(),
		})
		return
	}
	web.SuccessResponse(ctx, data)

}

func (s *serviceUsersApi) BatchUpdate(ctx *gin.Context) {
	var req request.BatchUpdateUserReq
	_ = ctx.BindJSON(&req)

	err := orm.GetDb().Model(&model.ServiceUser{}).Where("id in ?", req.UserIds).
		Updates(&req).Error
	if err != nil {
		web.FailResponse(ctx, err, "更新失败")
	} else {
		web.SuccessResponse(ctx, "更新成功")
	}
}

// 登录签发token
func (s *serviceUsersApi) generateUserToken(userInfo model.ServiceUser, ctx *gin.Context) {
	token, err := service.NewToken(userInfo.ID, userInfo.Password, userInfo.Role.UpdatedAt)
	if err != nil {
		core.GetLogger().Error("操作失败", zap.Error(err))
		web.FailResponse(ctx, err, "获取token失败!")
	}
	web.SuccessResponse(ctx, token)
}

// CreateServiceUsers 创建用户
func (s *serviceUsersApi) CreateServiceUsers(ctx *gin.Context) {
	var serviceUsers model.ServiceUser
	_ = ctx.BindJSON(&serviceUsers)
	if err := serviceUsersService.CreateUsers(serviceUsers); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// DeleteServiceUsers 删除用户
func (s *serviceUsersApi) DeleteServiceUsers(ctx *gin.Context) {
	var serviceUsers model.ServiceUser
	_ = ctx.BindJSON(&serviceUsers)
	if err := serviceUsersService.DeleteServiceUsers(serviceUsers); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// UpdateServiceUsers 更新用户
func (s *serviceUsersApi) UpdateServiceUsers(ctx *gin.Context) {
	var serviceUsers request.UpdateUserReq
	_ = ctx.BindJSON(&serviceUsers)
	if err := serviceUsersService.UpdateServiceUsers(serviceUsers); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// GetServiceUsersList 查询用户列表
func (s *serviceUsersApi) GetServiceUsersList(ctx *gin.Context) {
	var pageInfo request.ServiceUsersSearch
	_ = ctx.BindQuery(&pageInfo)

	err, list, total, dayCap, todayLen := serviceUsersService.GetServiceUsersList(pageInfo, ctx)
	if err != nil {
		web.FailResponse(ctx, err, err.Error())
		return
	}

	if list == nil {
		list = make([]model.ServiceUser, 0)
	}
	data := make(map[string]interface{})
	data["list"] = list
	data["total"] = total
	data["dayCap"] = dayCap
	data["todayLen"] = todayLen
	data["page"] = pageInfo.Page
	data["pageSize"] = pageInfo.PageSize
	//data["list"] = web.PageResult{
	//	List:     list,
	//	Total:    total,
	//	Page:     pageInfo.Page,
	//	PageSize: pageInfo.PageSize,
	//}
	//data["today_len"] = todayLen
	//data["day_cap"] = dayCap

	web.SuccessResponse(ctx, data)
}

// UpdatePassword 修改账号密码
func (s *serviceUsersApi) UpdatePassword(ctx *gin.Context) {
	var serviceUsers request.UpdatePasswordReq
	_ = ctx.BindJSON(&serviceUsers)
	if err := serviceUsersService.UpdatePassword(serviceUsers.ID, serviceUsers.Password); err != nil {
		web.FailResponse(ctx, err, err.Error())

	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// OldToNewPassword 修改密码
func (s *serviceUsersApi) OldToNewPassword(ctx *gin.Context) {
	var serviceUsers request.OldToNewResp
	_ = ctx.BindJSON(&serviceUsers)
	if err := serviceUsersService.OldToNewPassword(serviceUsers); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// GetUserDropDownBox 查询用户下拉框
func (s *serviceUsersApi) GetUserDropDownBox(ctx *gin.Context) {
	var pageInfo request.ServiceUsersSearch
	_ = ctx.BindQuery(&pageInfo)

	userId := service.GetUserID(ctx)
	data, err := orm.Detail[model.ServiceUser](userId, "Role")
	if err != nil {
		web.FailResponse(ctx, err, err.Error())
		return
	}

	if err, list, total := serviceUsersService.GetUserDropDownBox(pageInfo, data); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessListResponse(ctx, list, total, pageInfo.Page, pageInfo.PageSize)
	}
}
